package com.kawa.kemanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kawa.kemanage.entity.News;
import com.kawa.kemanage.entity.ContentReview;
import com.kawa.kemanage.entity.NewsDraft;
import com.kawa.kemanage.entity.User;
import com.kawa.kemanage.mapper.NewsMapper;
import com.kawa.kemanage.mapper.UserMapper;
import com.kawa.kemanage.service.NewsService;
import com.kawa.kemanage.service.ContentReviewService;
import com.kawa.kemanage.service.NewsDraftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Author: KAIyo
 * @Date: 2025/6/3 0:28
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class NewsServiceImpl implements NewsService {
    private static final Logger log = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ContentReviewService contentReviewService;

    @Autowired
    private NewsDraftService newsDraftService;

    /**
     * 查询新闻列表
     * @param pageNo
     * @param pageSize
     * @param categoryId
     * @param sortField
     * @param sortOrder
     * @return
     */
    @Override
    @Cacheable(value = "news", key = "'list-' + #pageNo + '-' + #pageSize + '-' + #categoryId + '-' + #sortField + '-' + #sortOrder", unless = "#result == null")
    public PageInfo<News> getNewsList(Integer pageNo, Integer pageSize, String categoryId, String sortField, String sortOrder) {
        PageHelper.startPage(pageNo, pageSize);
        String orderBy = sortField + " " + sortOrder;
        PageHelper.orderBy(orderBy);
        List<News> newsList = newsMapper.queryNewsList(categoryId);
        return new PageInfo<>(newsList);
    }

    /**
     * 删除
     * @param id 根据传入的id进行删除
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "news", allEntries = true)
    public int deleteNewsById(int id) {
        return newsMapper.deleteNewsById(id);
    }

    /**
     * 更新新闻方法
     * @param news
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "news", allEntries = true)
    public int updateNews(News news) {
        return newsMapper.updateNews(news);
    }

    /**
     *搜索新闻
     * @param keyword
     * @param categoryId
     * @param pageNo
     * @param pageSize
     * @param sortType
     * @return
     */
    @Override
    @Cacheable(value = "news", key = "'search-' + #keyword + '-' + #categoryId + '-' + #pageNo + '-' + #pageSize + '-' + #sortType", unless = "#result == null")
    public PageInfo<News> searchNews(String keyword, String categoryId, Integer pageNo, Integer pageSize, String sortType) {
        log.info("Searching news with params - keyword: {}, categoryId: {}, pageNo: {}, pageSize: {}, sortType: {}", 
                 keyword, categoryId, pageNo, pageSize, sortType);
        
        // 设置分页
        PageHelper.startPage(pageNo, pageSize);
        
        // 设置排序
        if ("time".equals(sortType)) {
            PageHelper.orderBy("createDate DESC");
        } else {
            // 默认按创建时间倒序
            PageHelper.orderBy("createDate DESC");
        }
        
        // 执行查询
        List<News> newsList = newsMapper.searchNews(keyword, categoryId, sortType);
        log.info("Found {} news items before pagination", newsList != null ? newsList.size() : 0);
        
        // 设置作者信息
        if (newsList != null && !newsList.isEmpty()) {
            newsList.forEach(news -> {
                if (news.getAuthorId() != null) {
                    try {
                        User user = userMapper.findById(news.getAuthorId());
                        if (user != null) {
                            news.setAuthor(user.getUserName());
                        }
                    } catch (Exception e) {
                        log.error("获取作者信息失败: {}", e.getMessage());
                    }
                }
            });
        }
        
        // 创建分页信息对象
        PageInfo<News> pageInfo = new PageInfo<>(newsList);
        log.info("Pagination info - total: {}, pages: {}, pageNum: {}, pageSize: {}", 
                 pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getPageSize());
        
        return pageInfo;
    }

    /**
     * 发布新闻
     * @param news
     * @return
     */
    @Override
    @Transactional
    @CacheEvict(value = "news", allEntries = true)
    public boolean addNews(News news) {
        return newsMapper.addNews(news) > 0;
    }

    /**
     * 发布新闻并创建审核记录
     * @param news 新闻信息
     * @param authorId 作者ID
     * @param draftId 草稿ID（可选）
     * @return 添加结果
     */
    @Override
    @Transactional
    @CacheEvict(value = "news", allEntries = true)
    public boolean addNewsWithReview(News news, Long authorId, Integer draftId) {
        // 设置新闻为未发布状态
        news.setIsPublish(0);
        LocalDateTime now = LocalDateTime.now();
        news.setModifyDate(now);
        news.setCreateDate(now);

        // 添加新闻
        boolean newsResult = newsMapper.addNews(news) > 0;

        if (newsResult && news.getId() > 0) {
            // 创建审核记录
            ContentReview review = new ContentReview();
            review.setContentId(Long.valueOf(news.getId()));
            review.setReviewerId(null); // 待审核
            review.setReviewStatus("pending");
            review.setReviewComments("");

            boolean reviewResult = contentReviewService.createReview(review);

            // 如果有草稿ID，删除对应的草稿
            if (draftId != null && reviewResult) {
                try {
                    newsDraftService.deleteDraft(draftId);
                } catch (Exception e) {
                    // 记录错误但不影响主流程
                    log.error("删除草稿失败，草稿ID: " + draftId, e);
                }
            }

            return reviewResult;
        }

        return false;
    }

    /**
     * 获取热门新闻列表
     * @return 热门新闻列表
     */
    @Override
    @Cacheable(value = "news", key = "'hot'", unless = "#result == null")
    public List<News> getHotNews() {
        return newsMapper.getHotNews();
    }

    /**
     *
     * 获取新闻详情
     * @param newsId 新闻ID
     * @return
     */
    @Override
    @Cacheable(value = "news", key = "'detail-' + #newsId", unless = "#result == null")
    public News getNewsById(String newsId) {
        return newsMapper.queryNewsById(newsId);
    }
    /**
     * 根据用户名查看作品
     * @param authorId
     * @return
     */
    @Override
    public List<News> getNewsByName(Integer authorId) {
        return newsMapper.getNewsByName(authorId);
    }

    /**
     * 获取个人收藏的作品
     * @param user_id
     * @return
     */
    @Override
    public List<News> getNewsByFavorite(Integer user_id) {
        return newsMapper.getNewsByFavorite(user_id);
    }

    //喜欢的作品
    @Override
    public List<News> getNewsByLike(Integer user_id) {
        return newsMapper.getNewsByLike(user_id);
    }

    @Override
    public List<News> getRelatedNews(String newsId, Integer limit) {
        return newsMapper.getRelatedNews(newsId, limit);
    }

}
